package com.seven.system.service.Impl;

import com.seven.enity.Permission;
import com.seven.system.dao.PermissionDao;
import com.seven.system.service.PermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author longlong
 * @date 2024/3/6 15:44
 * description
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Resource
    private PermissionDao permissionDao;

    @Override
    public List<Permission> getPermissionListByUserId(String userId) {
        return permissionDao.selectPermissionListByUserId(userId);

    }

    @Override
    public List<Permission> getLeftMenuByUserName(String username) {
        //1.获取自身所有的权限
        List<Permission> permissions = permissionDao.selectPermissionListByUserName(username);
        //2.封装返回格式--递归实现
        //父子菜单编号为 1
        List<Permission> first = permissions.stream().filter(item -> item.getPid().equals("1")).collect(Collectors.toList());
        for (Permission p:first){
            List<Permission> children = getChildren(p.getId(), permissions);
            p.setChildren(children);
        }
        return first;
    }

    /**
     * 递归获取子菜单
     * @return
     */
    private List<Permission> getChildren(String pid,List<Permission> permissions){
        //子菜单对象
        List<Permission> children=new ArrayList<>();
        for(Permission p:permissions){
            if(p.getPid().equals(pid)){
                children.add(p);
            }
        }
        //遍历二级菜单
        for(Permission c:children){
            List<Permission> children1 = getChildren(c.getId(), permissions);
            c.setChildren(children1);
        }
        return children;
    }
}
